//
//  XLHTTPSessionManager+Analytics.m
//  XiangLove
//
//  Created by 陈宪栋 on 2017/12/6.
//  Copyright © 2017年 BAOMIHUA.COM. All rights reserved.
//

#import "XLHTTPSessionManager+Analytics.h"
//#import <UIApplication+YYAdd.h>
#import <ReactiveCocoa.h>
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"
#import <objc/runtime.h>

//@implementation LCBaseEventHandler (Analytics)lemonsdk
//- (NSTimeInterval)resumeTime {
//    return [objc_getAssociatedObject(self, @"resumeTime") doubleValue];
//}
//
//- (NSTimeInterval)completeTime {
//    return [objc_getAssociatedObject(self, @"completeTime") doubleValue];
//}
//
//- (void)setResumeTime:(NSTimeInterval)resumeTime {
//    objc_setAssociatedObject(self, @"resumeTime", @(resumeTime), OBJC_ASSOCIATION_RETAIN);
//}
//
//- (void)setCompleteTime:(NSTimeInterval)completeTime {
//    objc_setAssociatedObject(self, @"completeTime", @(completeTime), OBJC_ASSOCIATION_RETAIN);
//}
//@end

@interface NSURLSessionTask (Analytics)
@property (nonatomic, assign) NSTimeInterval resumeTime;
@property (nonatomic, assign) NSTimeInterval completeTime;
@end

@implementation NSURLSessionTask (Analytics)
- (NSTimeInterval)resumeTime {
    return [objc_getAssociatedObject(self, @"resumeTime") doubleValue];
}

- (NSTimeInterval)completeTime {
    return [objc_getAssociatedObject(self, @"completeTime") doubleValue];
}

- (void)setResumeTime:(NSTimeInterval)resumeTime {
    objc_setAssociatedObject(self, @"resumeTime", @(resumeTime), OBJC_ASSOCIATION_RETAIN);
}

- (void)setCompleteTime:(NSTimeInterval)completeTime {
    objc_setAssociatedObject(self, @"completeTime", @(completeTime), OBJC_ASSOCIATION_RETAIN);
}
@end

@interface AFURLSessionManager (Analytics)

@end

@implementation AFURLSessionManager (Analytics)
+ (void)load {
    Method method1 = class_getInstanceMethod([self class], @selector(URLSession:task:didCompleteWithError:));
    Method method2 = class_getInstanceMethod([self class], @selector(analytics_URLSession:task:didCompleteWithError:));
    method_exchangeImplementations(method1, method2);
    
    Method method3 = class_getInstanceMethod([self class], @selector(dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:));
    Method method4 = class_getInstanceMethod([self class], @selector(analytics_dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:));
    method_exchangeImplementations(method3, method4);
}

- (NSURLSessionDataTask *)analytics_dataTaskWithRequest:(NSURLRequest *)request
                                         uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
                                       downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
                                      completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject,  NSError * _Nullable error))completionHandler {
    NSURLSessionDataTask *task = [self analytics_dataTaskWithRequest:request uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler];
    task.resumeTime = [[NSDate date] timeIntervalSince1970];
    return task;
}

- (void)analytics_URLSession:(NSURLSession *)session
                        task:(NSURLSessionTask *)task
        didCompleteWithError:(NSError *)error {
    task.completeTime = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval responseTime = task.completeTime - task.resumeTime;
    NSString *url = task.currentRequest.URL.absoluteString;
    NSString *body = [[NSString alloc] initWithData:task.originalRequest.HTTPBody encoding:NSUTF8StringEncoding];
    NSLog(@"AFNetWorking\nHTTPURL:\n%@\n\nHTTPBody:\n%@\n\nResponseTime:\n%fms\n", url, body, responseTime * 1000);
    [self analytics_URLSession:session task:task didCompleteWithError:error];
}

@end

@implementation XLHTTPSessionManager (Analytics)

+ (instancetype)sharedAnalyticsManager {
    static dispatch_once_t onceToken;
    static XLHTTPSessionManager *instance;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"http://xinliaolog.interface.baomihua.com"]];
        instance.requestSerializer = [AFHTTPRequestSerializer serializer];
        [[NSNotificationCenter defaultCenter] addObserver:instance selector:@selector(inviteVideoChatMessage:) name:@"inviteVideoChatMessage" object:nil];
    });
    return instance;
}

- (RACSignal *)analyticsModule:(NSString *)module action:(NSString *)action userId:(NSString *)userId camgirlId:(NSString *)camgirlId {
    NSString *URLString = @"/Api/HeartChatLog/WriterLog";
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"statistics" forKey:@"logType"];
    [parameters setObject:@"2" forKey:@"phoneType"];
    [parameters setObject:@"null" forKey:@"remake"];
    [parameters setObject:QudaoName forKey:@"qudao"];
    [parameters setObject:module ?: @"" forKey:@"module"];
    [parameters setObject:action ?: @"" forKey:@"action"];
    [parameters setObject:F(@"%@,%@,%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"], userId ?: @"", camgirlId ?: @"") forKey:@"extend"];
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        NSURLSessionDataTask *task = [self GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [subscriber sendNext:responseObject];
            [subscriber sendCompleted];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [subscriber sendError:error];
        }];
        return [RACDisposable disposableWithBlock:^{
            [task cancel];
        }];
    }];
}

#pragma mark -
- (void)inviteVideoChatMessage:(NSNotification *)notification {
    NSString *camgirlId = notification.object;
    [[self analyticsModule:@"xl_message" action:@"invite_videochat" userId:[[XLAccountManager shareInstance] model].Id camgirlId:camgirlId] subscribeNext:^(id x) {
        
    } error:^(NSError *error) {
        
    }];
}
@end
